#include <tsin/library/TouhouPlayerSeries.hpp>

#include <tsin/library/BuiltinImages.hpp>

#include <tsin/util/Logger.hpp>

using namespace tsin;

static const int TICKS_PER_FRAME = 5;
static const int TOTAL_FRAMES = 8;

static void animation(DecoratedImage *image, int prevTick, int curTick)
{
        if (curTick == image->nrFrames()) {
                image->setFrame(0, false);
                curTick = 0;
        }

        int prevFrame = prevTick / TICKS_PER_FRAME;
        int curFrame = curTick / TICKS_PER_FRAME;
        if (prevFrame == curFrame)
                return;

        float l = image->left(), r = image->right(), w = image->width();
        int relative = curFrame - prevFrame;
        image->setXRange(l + relative*w, r + relative*w);
}

static void lrAnimation(DecoratedImage *image, int prevTick, int curTick)
{
        if (curTick == image->nrFrames()) {
                int next = image->nrFrames() / 2;
                image->setFrame(next, false);
                curTick = next;
        }

        int prevFrame = prevTick / TICKS_PER_FRAME;
        int curFrame = curTick / TICKS_PER_FRAME;
        if (prevFrame == curFrame)
                return;

        float l = image->left(), r = image->right(), w = image->width();
        int relative = curFrame - prevFrame;
        image->setXRange(l + relative*w, r + relative*w);
}

const char *TouhouPlayerSeries::getImagePath()
{
        switch (character) {
        case KIRISAME_MARISA:
                return RES_PREFIX "player/marisa_all.png";;
        default:
                return RES_PREFIX "player/reimu_all.png";
        }
}

int TouhouPlayerSeries::getSizeX()
{
        return 32;
}

int TouhouPlayerSeries::getSizeY()
{
        return 48;
}

int TouhouPlayerSeries::getCoordX()
{
        return 0;
}

int TouhouPlayerSeries::getCoordY()
{
        switch(action) {
        case MOVE_LEFT:
                return 160;
        case MOVE_RIGHT:
                return 112;
        default:
                return 208;
        }
}

int TouhouPlayerSeries::getNrFrames()
{
        return TICKS_PER_FRAME * TOTAL_FRAMES;
}

NextFrameHandler TouhouPlayerSeries::getHandler()
{
        switch(action) {
        case MOVE_LEFT:
        case MOVE_RIGHT:
                return lrAnimation;
        default:
                return animation;
        }
}
